package com.newsproject.service.impl;

import Util.FormatTime;

import com.newsproject.mapper.NewsMapper;
import com.newsproject.mapper.PostMapper;
import com.newsproject.mapper.SearchInUserPageMapper;
import com.newsproject.mapper.UserMapper;
import com.newsproject.pojo.*;
import com.newsproject.pojo.DTO.AccountUser;
import com.newsproject.pojo.DTO.OtherUserDTO;
import com.newsproject.pojo.DTO.PostDTO;
import com.newsproject.pojo.DTO.UpdatePost;
import com.newsproject.pojo.vo.PublishPost;
import com.newsproject.pojo.vo.CommentVo;
import com.newsproject.service.PostService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.HashMap;

@Slf4j
@Service
public class PostServiceImpl implements PostService{

    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private SearchInUserPageMapper searchInUserPageMapper;
    @Autowired
    private MinioServiceImpl minioServiceImpl;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;

    private static final int PAGE_SIZE = 10;

    public boolean cheaklogin(HttpSession session)
    {
        if (session.getAttribute("userInfo") == null)
            return false;
        else return true;
    }

    //新闻转发
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> sharePost(int postId,int forwardedId,HttpSession session) {
        Result<Object> result=new Result<>();
        if(!cheaklogin(session))
        {
            result.setCode(400);
            result.setMessage("请先登录");
            return result;
        }
        Post post=newsMapper.selectPostByPostId(postId);
        User forward=newsMapper.selectbyId(forwardedId);
        if(forward==null||post==null)
        {
            result.setCode(400);
            result.setMessage("转发失败，当前新闻或转发用户不存在");
            return result;
        }
        User user=(User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        Repost repost=new Repost();
        repost.setUserId(userId);
        repost.setCreatedTime(new Date());
        repost.setForwardedId(forwardedId);
        repost.setPostId(postId);
        if(newsMapper.insertRepost(repost))
        {
            int shareCount=post.getShareCount();
            newsMapper.incrementShareCount(postId);
            result.setCode(200);
            result.setMessage("转发成功");
            result.setData(shareCount);
        }
        else{
            result.setCode(400);
            result.setMessage("转发失败");
        }
        return result;
    }
    //关注
    @Transactional
    @Override
    public Result<Object> follower(int followedId,HttpSession session) {
        Result<Object> result = new Result<>();
        if (cheaklogin(session)) {
            User userInfo = (User) session.getAttribute("userInfo");
            int userId = userInfo.getUserId();
            int count = newsMapper.checkfollow(userId, followedId);
            if (count > 0)//判断是否关注过，关注过则取消关注
            {
                newsMapper.delectfollower(userId, followedId);
                userMapper.declineFollowerCount(followedId);
                userMapper.declineBookmarkCount(userId);
                result.setMessage("取消关注");
                result.setCode(200);
            } else {
                Follow follow = new Follow();
                follow.setFollowerId(userId);
                follow.setFollowedId(followedId);
                newsMapper.follower(follow);
                userMapper.addFollowerCount(followedId);
                userMapper.addBookmarkCount(userId);
                result.setMessage("成功关注");
            }
        } else {
            result.setMessage("请先登录");
            result.setCode(400);
        }
        return result;
    }
    //评论点赞并返回点赞数
    @Transactional
    @Override
    public Result<Object> insertLike(int commentId, HttpSession session){
        User user=(User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        Result<Object>result=new Result<>();
        if (cheaklogin(session)) {
            Map<String, Object> parames = new HashMap<>();
            parames.put("userId", userId);
            parames.put("commentId", commentId);
            int count = newsMapper.checkLikeRecord(parames);
            Comment comment = newsMapper.selectcomment(commentId);
            if(comment==null) {
                  result.setCode(400);
                  result.setMessage("当前评论不存在");
                  return result;
            }
            //判断用户是否点赞过该评论
            if (count > 0) {
                newsMapper.deleteLike(parames);//用户已经点赞过这个评论,再次点赞就会取消点赞
            } else {
                newsMapper.insertLike(userId, commentId);
            }
            int likecount=newsMapper.countCommentLike(commentId);
            newsMapper.updateCommentlikeCount(likecount,commentId);
            result.setCode(200);
            result.setData(likecount);
       }
        else{
           result.setCode(400);
           result.setMessage("请先登录");
        }
        return result;
    }

    //新闻点赞操作
    @Override
    @Transactional
    public Result<Integer> intserHeart(int postId,HttpSession session)
    {
        Result<Integer> result=new Result<>();
        if(cheaklogin(session)) {
            Post post = newsMapper.selectPostByPostId(postId);
            if(post==null) {
                result.setCode(400);
                result.setMessage("该新闻不存在,postId输入错误"+postId);
                return result;
            }
            User userInfo = (User)session.getAttribute("userInfo");
            Integer userId= userInfo.getUserId();
            Integer likeId = newsMapper.checkHearyRecord(userId,postId);
            //判断用户是否点赞过该新闻
            if (likeId != null) {
                newsMapper.deleteHeartById(likeId);//用户已经点赞过这个新闻，则取消点赞
                newsMapper.deletepostLike(postId);
                userMapper.declinePrizeCount(post.getUserId());
                result.setMessage("取消点赞");
            } else {
                userMapper.addPrizeCount(post.getUserId());
                newsMapper.insertHeart(userId, postId);
                newsMapper.addpostLike(postId);
                result.setMessage("点赞成功");
            }
            result.setCode(200);
            post = newsMapper.selectPostByPostId(postId);
            result.setData(post.getLikeCount());
        }
        else{
            result.setCode(400);
            result.setMessage("请先登录");
        }
        return result;
    }
    //收藏操作
    @Transactional
    @Override
    public Result<Object> intserbookmark(int postId,HttpSession session)
    {
        Result<Object> result=new Result<>();
        if(cheaklogin(session)){
            User userInfo = (User)session.getAttribute("userInfo");
            Integer userId= userInfo.getUserId();
            int bookOrNot = newsMapper.checkbookmark(userId, postId);
            //判断用户是否收藏过该新闻
            if(bookOrNot==0) {
                //用户没有收藏过这个新闻
                newsMapper.insertbookmark(userId, postId);
                newsMapper.addbookmarkCount(postId);
                result.setMessage("收藏成功");
                result.setCode(200);
            }else {
                newsMapper.deletebookmark(userId,postId);//用户已经收藏过这个新闻
                newsMapper.declinebookmarkCount(postId);//取消收藏
                result.setMessage("取消收藏");
                result.setCode(200);
            }
        }
        else{
               result.setCode(400);
               result.setMessage("请先登录");
        }
        return result;
    }


    //添加评论
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> insertComment(String content,int parentId,HttpSession session)
    {
        Result<Object> result=new Result<>();
        if(!cheaklogin(session)) {
           result.setCode(400);
           result.setMessage("请先登录");
           return result;
        }
        User user=(User)session.getAttribute("userInfo");
        AccountUser accountUser = (AccountUser) session.getAttribute("account");
        if(accountUser.getCommentStatus()==0)
        {
            result.setCode(400);
            result.setMessage("您的评论已被禁用");
            return result;
        }
        int userId=user.getUserId();
        Comment comment=new Comment();
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setParentId(parentId);
        Comment parentComment=newsMapper.selectcomment(comment.getParentId());
            if(parentComment==null)
            {
                result.setCode(400);
                result.setMessage("无法回复");
                return result;
            }
            comment.setPostId(parentComment.getPostId());
        if (newsMapper.insertComment(comment)){
            int postId = comment.getPostId();
            newsMapper.addCommentCount(postId);
            Post post=newsMapper.selectPostByPostId(postId);
            int commentcount=post.getCommentCount();
            result.setCode(200);
            result.setData(commentcount);
        } else {
            result.setCode(400);
            result.setMessage("回复失败");
        }
        return result;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> deleteComment(int commentId,HttpSession session) {
        Result<Object> result = new Result<>();
        if (!cheaklogin(session)) {
            result.setCode(400);
            result.setMessage("请先登录");
            return result;
        }
        User user = (User) session.getAttribute("userInfo");
        int userId = user.getUserId();
        Comment comment = newsMapper.selectcomment(commentId);
        if (comment == null) {
            result.setCode(400);
            result.setMessage("评论删除失败");
            return result;
        }
        int userId1 = comment.getUserId();
        if (userId != userId1) {
            result.setCode(400);
            result.setMessage("评论删除失败,只能删除自己发布的评论");//只能删除自己发布的评论
            return result;
        }
        int postId = comment.getPostId();
        if (newsMapper.deleteComment(commentId)) {
            newsMapper.commentCount(postId);
            result.setCode(200);
            result.setMessage("评论删除成功");
        } else {
            result.setCode(400);
            result.setMessage("评论删除失败");
        }
        return result;
    }
    //判断评论状态
    @Override
    public Result<Map<String, Object>> commentstatus(int commentId, HttpSession session) {

        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response = new HashMap<>();
        User userInfo = (User)session.getAttribute("userInfo");
        if(userInfo==null){
            response.put("likeStatus",false);
            response.put("replyStatus",false);
            result.setData(response);
            result.setMessage("请先登录");
            result.setCode(400);
            return result;
        }
        Comment comment = newsMapper.selectcomment(commentId);
        if(comment==null) {
            response.put("likeStatus",false);
            response.put("replyStatus",false);
            result.setCode(400);
            result.setMessage("当前评论不存在");
            return result;
        }
        Integer userId = userInfo.getUserId();
        Map<String, Object> parames = new HashMap<>();
        parames.put("userId", userId);
        parames.put("commentId", commentId);
        Integer likeStatus = newsMapper.checkLikeRecord(parames);
        Integer reply=newsMapper.selectparentcount(commentId);
        Integer replyStatus=0;
        if(reply>0)
        {
            replyStatus=1;
        }
        response.put("likeStatus",likeStatus);
        response.put("replyStatus",replyStatus);
        result.setData(response);
        result.setCode(200);
        return result;
    }
    /**
     * 生成当前请求的完整URL
     * @param request HttpServletRequest对象
     * @return 当前请求的完整URL
     */
    public  Result<Object> getCurrentUrl(HttpServletRequest request) {
        Result<Object> result=new Result<>();
        StringBuffer url = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null) {
            url.append("?").append(queryString);
        }
        String Url=url.toString();
        result.setCode(200);
        result.setMessage("复制链接成功");
        result.setData(Url);
        return result;
    }
    //获取粉丝列表
    @Override
    public Result<Map<String ,Object>> followerList(Integer pageNum,HttpSession session)
    {
       Result<Map<String,Object>> result=new Result<>();
       //计算起始索引
        if(pageNum <=0){
            pageNum =1 ;
        }
       Integer startIndex=(pageNum-1)*10;
       //获取当前用户
       User user = (User)session.getAttribute("userInfo");
       Integer userId= user.getUserId();
       //获取粉丝数量
        Integer totalCount = userMapper.countFollower(userId);
        log.info("totalCount:{}",totalCount);
       //获取粉丝列表
       boolean hasMore = (startIndex+10<totalCount);
       List<OtherUserDTO> followerList = userMapper.selectFollowerList(userId, userId, startIndex);
       if(totalCount==0) {
           return result.error("没有粉丝");
       }
       Map<String,Object> response=new HashMap<>();
       response.put("hasMore",hasMore);
       response.put("totalCount",totalCount);
       response.put("followers", followerList);
       result.setData(response);
       result.setCode(200);
       return result;
    }
    //获取关注列表
    @Override
    public Result<Map<String ,Object>> followedList(Integer pageNUm,HttpSession session)
    {
        Result<Map<String ,Object>> result=new Result<>();
        Map<String,Object> response=new HashMap<>();
        //计算起始索引·
        if(pageNUm <=0){
            pageNUm =1 ;
        }
        Integer startIndex=(pageNUm-1)*10;
        if(!cheaklogin(session))
        {
            result.setCode(400);
            result.setMessage("请先登录");
            return result;
        }
        //获取当前用户id
        User user = (User)session.getAttribute("userInfo");
        Integer userId= user.getUserId();
        //获取关注数量
        Integer  totalCount =userMapper.countFollowed(userId);
        log.info("totalCount:{}",totalCount);

        List<OtherUserDTO> followedList = userMapper.findFollowedList(userId, userId, startIndex);
        if(totalCount == 0){
            result.setCode(400);
            result.setMessage("没有关注");
            return result;
        }
        boolean hasMore = (startIndex+10<totalCount);
        response.put("hasMore",hasMore);
        response.put("totalCount",totalCount);
        response.put("followedList",followedList);
        result.setData(response);
        result.setCode(200);
        return result;
    }
    //关注总数
    //关注总数
    @Override
    public Result<Object> countfollower(HttpSession session)
    {
        Result<Object>result=new Result<>();
        if(!cheaklogin(session))
        {
            result.setCode(400);
            result.setMessage("请先登录");
            return  result;
        }
        User user=(User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        int count=newsMapper.countFollower(userId);
        result.setCode(200);
        result.setData(count);
        return result;
    }
    //粉丝总数
    @Override
    public Result<Object> countfollowed(HttpSession session)
    {
        Result<Object>result=new Result<>();
        if(!cheaklogin(session))
        {
            result.setCode(400);
            result.setMessage("请先登录");
            return  result;
        }
        User user=(User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        int count=newsMapper.countFollowed(userId);
        result.setCode(200);
        result.setData(count);
        return result;
    }
    //查询用户点赞的新闻
    @Override
    public Result<List<Post>> HeartList(HttpSession session)
    {
        Result<List<Post>> result=new Result<>();
        if(!cheaklogin(session)) {
            result.setCode(400);
            result.setMessage("请先登录");
            return result;
        }
        User user= (User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        List<Post> heartLists=newsMapper.selectHeartList(userId);
        if(heartLists==null)
        {
            result.setMessage("暂无点赞");
        }else {
            result.setData(heartLists);
        }
        return result;
    }
    //查询用户收藏的新闻列表
    @Override
    public Result<List<Post>> BookmarkList(HttpSession session)
    {
        Result<List<Post>> result=new Result<>();
        if(!cheaklogin(session))
        {
            result.setCode(400);
            result.setMessage("请先登录");
            return result;
        }
        User user= (User)session.getAttribute("userInfo");
        int userId=user.getUserId();
        List<Post> posts=newsMapper.bookmarkList(userId);
        if(posts==null)
        {
            result.setCode(200);
            result.setMessage("暂无收藏");
        }
        else{
            result.setCode(200);
            result.setData(posts);
        }
        return result;
    }
    @Override
    public Result<Map<String,Object>> getCommentsWithReplies(Integer postId) {
        Result<Map<String,Object>> result=new Result<>();
        List<Comment> comments=newsMapper.selectCommentsByPostId(postId);
        int totalCount=newsMapper.countcomment(postId);
        Map<String,Object> response=new HashMap<>();
        response.put("totalCount",totalCount);
        response.put("comments",comments);



        if(comments==null)
        {
            result.setCode(400);
            result.setMessage("暂无评论");
        }
        else{
            result.setCode(200);
            result.setData(response);
        }
        return result;
    }
//查询用户的总获赞数
    @Override
    public Integer countAlllike(Integer userId) {
        return newsMapper.countAlllike(userId);
    }

    @Override
    @Transactional
    public String deletePost(Integer postId) {
        newsMapper.deletebookmark(0,postId);
        newsMapper.deleteHotPost(postId);
        newsMapper.deleteCommentByPostId(postId);
       if(newsMapper.deletePostByPostId(postId)==1) {
           return "删除成功";
       }
       else{
           return "删除失败";
       }
    }

   static  final Map<Integer,String> tags=new HashMap<>();
    static {
        tags.put(1,"recommend-content");
        tags.put(2,"follows-content");
        tags.put(3,"finance-content");
        tags.put(4,"technology-content");
        tags.put(5,"hot-content");
        tags.put(6,"military-content");
        tags.put(7,"sports-content");
        tags.put(8,"entertainment-content");
        tags.put(9,"history-content");
        tags.put(10,"food-content");
        tags.put(11,"car-content");
        tags.put(12,"直播");
        tags.put(13,"travel-content");
    }

    @Override
    public ModelAndView getPostByPageAndTagId(Integer pageNum,Integer pageSize,Integer tagId,HttpSession session) {
        ModelAndView mv =new ModelAndView();
        //定位到对应的页面
        Set<Map.Entry<Integer, String>> entries = tags.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            if (entry.getKey() == tagId) {
                mv.setViewName(entry.getValue());
            }
        }
        // 计算起始索引
        int startIndex = (pageNum - 1) * pageSize;
        //每日热搜的post
        if(tagId==1) {
            List<HotSearch> todayHotSearch = newsMapper.selectTodayHotSearch(0, 5);
            mv.addObject("todayHotSearch", todayHotSearch);
        }
        // 获取当前页面的数据
        List<PostDTO> posts = newsMapper.selectPostByPageAndTagId(startIndex, pageSize, tagId);

        //格式化时间
        posts.forEach(post->{
            String formatTime = FormatTime.formatTimeDifference(post.getTime());
            post.setCreatedTime(formatTime);
        });
        // 计算总条数
        Integer totalCount = newsMapper.selectTotalCountByTagId(tagId);
        //判断是否有下一页
        boolean hasMore = (startIndex + pageSize) < totalCount;
        if(!hasMore){
            mv.addObject("hasMore",hasMore);
            mv.addObject("message","没有更多内容了");
        }


        //总热搜的post
        List<HotSearch> totalHotSearch = newsMapper.selectHotSearch();
        User userInfo = (User) session.getAttribute("userInfo");
        mv.addObject("userInfo",userInfo);
        mv.addObject("totalHotSearch",totalHotSearch);
        mv.addObject("posts",posts);
        return mv;
    }

    @Override
    public Result<Map<String ,Object>> findPostByPageAndTagId(Integer pageNum, Integer pageSize, Integer tagId) {
        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response=new HashMap<>();
        if(pageNum <=0 ){
            pageNum =1;
        }
        //计算起始索引
        Integer startIndex = (pageNum - 1) * pageSize;
        boolean hasMore ;
        List<PostDTO> posts = newsMapper.selectPostByPageAndTagId(startIndex, pageSize, tagId);
        if(posts.size() == 0){
            hasMore =false;
            response.put("hasMore",hasMore);
            result.setCode(200);
            return result;
        }
        //而格式化时间
        posts.forEach(post->{
            String formatTime = FormatTime.formatTimeDifference(post.getTime());
            post.setCreatedTime(formatTime);
        });
        //获取总条数
        Integer totalCount = newsMapper.selectTotalCountByTagId(tagId);
        //判断是否有下一页
        hasMore = (startIndex + pageSize) < totalCount ;
        log.info("hasMore:{}",hasMore);
        log.info("totalCount:{}",totalCount);
        log.info("pageSize:{}",pageSize);
        log.info("startIndex:{}",startIndex);
        response.put("posts",posts);
        response.put("hasMore",hasMore);
        result.setData(response);
        result.setCode(200);
        return result;
    }


    @Override
    public ModelAndView getEssayPage(Integer postId,HttpSession session) {
        ModelAndView mv=new ModelAndView();
        User user = (User)session.getAttribute("userInfo");
        Post post = newsMapper.selectPostByPostId(postId);
        Map<String,Object> param=new HashMap<>();
        param.put("userId",post.getUserId());
        User author = userMapper.selectUserByUserIdOrEmail(param);
        List<CommentVo> allComments = newsMapper.selectAllCommentByPostId(postId);
        if(post==null){
            mv.addObject("message","该文章不存在");
            mv.setViewName("redirect:/user/mainPage");
            return mv;
        }
        List<CommentVo> commentVos = newsMapper.selectFourCommentByPostId(postId);
        //增加文章阅读量
        newsMapper.updateViewCount(postId);

        mv.addObject("userInfo",user);
        mv.addObject("author",author);       //作者信息
        mv.addObject("comments", commentVos);
        mv.addObject("allComments", allComments);//全部评论
        mv.addObject("post", post);
        mv.setViewName("Essay-page");
        return mv;
    }

    @Override
    public Result<Map<String,Object>> getFollowerPost(HttpSession session,int start ,int pageSize) {
        User userInfo = (User) session.getAttribute("userInfo");
        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response=new HashMap<>();
        //如果用户没有登陆
        if(userInfo==null){
            result.setMessage("用户尚未登录");
            result.setCode(400);
            return result;
        }
        int startIndex = (start - 1) * pageSize;
        //获取当前页面的数据
        List<PostDTO> posts = newsMapper.selectPostByFollowedId(startIndex,pageSize, userInfo.getUserId());
        posts.forEach(post->{
            String formatTime = FormatTime.formatTimeDifference(post.getTime());
            post.setCreatedTime(formatTime);
        });
        //获取总数
        int totalCount = newsMapper.totalCountByFollowedId(userInfo.getUserId());
        if(totalCount == 0){
            response.put("hasMore",false);
            response.put("message","没有更多内容了");
        }
        boolean hasMore = (start + pageSize) < totalCount;
        response.put("hasMore",hasMore);
        response.put("posts",posts);
        response.put("totalCount",totalCount);
        result.setCode(200);
        result.setData(response);
        return result;
    }


    @Scheduled(fixedRate = 60*60*60 * 1000)
    @Override
    public void searchAndStoreHotPost() {
        List<Post> posts = newsMapper.calculateAndCompareHot();
        List<Integer> list = newsMapper.selectHotPostId();
        LinkedList<Integer> linkedList = new LinkedList<>(list);
        posts.forEach(post ->{
            if(linkedList.contains(post.getPostId())){
                newsMapper.deleteHotPost(post.getPostId());
            }
        } );
        if(!posts.isEmpty()){
            newsMapper.insertHotPost(posts);
        }

    }












    @Override
    public Result<Map<String,Object>> getAllCommentByPage(Integer postId,Integer pageNum) {
        if(pageNum <=0 || postId == null){
            return Result.error("参数错误");
        }
        Map<String,Object> response=new HashMap<>();
        //计算起始索引
        int startIndex = (pageNum - 1) * 6;
        //获取总条数
        int totalCount = postMapper.selectCommentCountByPostId(postId);
        //获取每页评论
        List<CommentVo> comments = postMapper.selectAllCommentByPostId(postId, startIndex);
        //格式化时间
        if(comments.isEmpty()){
            response.put("hasMore",false);
            return Result.success(response);
        }
        comments.forEach(comment -> {
            String time = FormatTime.formatTimeDifference(comment.getTime());
            comment.setCreatedTime(time);
        });
        //判断是否有下一页
        boolean hasMore = (startIndex + 6) < totalCount;
        response.put("comments",comments);
        response.put("hasMore",hasMore);
        return Result.success(response);
    }

    @Override
    public void deleteComment(Integer commentId) {
        newsMapper.deleteByCommentId(commentId);
    }
    static final Map<Integer,String> category=new HashMap<>();
    static {
        category.put(1,"推荐");
        category.put(2,"关注");
        category.put(3,"财经");
        category.put(4,"科技");
        category.put(5,"热点");
        category.put(6,"军事");
        category.put(7,"体育");
        category.put(8,"娱乐");
    }
    @Override
   public Result<Object> post(PublishPost post,MultipartFile coverImage,MultipartFile image, HttpSession session) throws Exception {
            User userInfo = (User)session.getAttribute("userInfo");
            Result<Object> result=new Result<>();

            String cover = minioServiceImpl.uploadImage(coverImage);
            String url="";
            if(image!= null){
                url = minioServiceImpl.uploadImage(image);
                log.info("url:"+url);
            }
            if(coverImage.isEmpty()){
                return Result.error("封面不能为空");
            }
            if(post.getTitle()== null || post.getTitle().trim().equals("")){
                return Result.error("标题不能为空");
            }


            Post newsPost = new Post();
            newsPost.setTitle(post.getTitle());
            newsPost.setContent(post.getContent());
            newsPost.setCoverImage(cover);
            newsPost.setUserId(userInfo.getUserId());
            newsPost.setTagId(post.getTagId());
            newsPost.setPicture(url);
            newsPost.setTextStatus(post.getTextStatus());
            newsPost.setIsMemberOnly(post.getIsMemberOnly());

            newsMapper.insertPost(newsPost);
            log.info("cover:"+coverImage.getContentType());

            result.setCode(200);
            result.setMessage("发布成功");
            return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String,Object>> comment(String content, Integer postId, HttpSession session) {
        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response = new HashMap<>();
        if(cheaklogin(session)){
            AccountUser accountUser = (AccountUser)session.getAttribute("account");
            if(newsMapper.selectPostByPostId(postId)==null){
                result.setMessage("该文章不存在");
                result.setCode(400);
                return result;
            }
            if(accountUser.getCommentStatus() ==0){
                result.setMessage("您已被禁言");
                result.setCode(400);
                return result;
            }
            // 插入评论
            newsMapper.comment(content,accountUser.getUserId(),postId);
            // 更新评论数
            newsMapper.addCommentCount(postId);

            List<CommentVo> commentVos = newsMapper.selectFourCommentByPostId(postId);
            List<CommentVo> allCommentVos = newsMapper.selectAllCommentByPostId(postId);
            Post post = newsMapper.selectPostByPostId(postId);
            int CommentCount = post.getCommentCount();
            response.put("fourComments", commentVos);
            response.put("allComments", allCommentVos);
            response.put("CommentCount", CommentCount);
            result.setData(response);
            result.setCode(200);
        }
        else {
            result.setMessage("请先登录");
            result.setCode(400);
        }
        return result;
    }
    @Override
    public Result<Map<String, Object>> getSomeStatus(Integer postId, HttpSession session) {

        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response = new HashMap<>();
        User userInfo = (User)session.getAttribute("userInfo");
        if(userInfo==null){
            response.put("likeStatus",false);
            response.put("bookStatus",false);
            response.put("followStatus",false);
            result.setData(response);
            result.setMessage("没登陆");
            result.setCode(400);
            return result;
        }
        Integer userId = userInfo.getUserId();

        Integer likeStatus = postMapper.selectLikeStatusByPostIdAndUserId(postId, userId);
        Integer bookStatus = postMapper.selectBookmarkOrNotByUserIdAndPostId(postId, userId);
        Integer followStatus = postMapper.selectFollowOrNotByUserIdAndAuthorId(postId, userId);

        response.put("likeStatus",likeStatus);
        response.put("bookStatus",bookStatus);
        response.put("followStatus",followStatus);
        result.setData(response);
        result.setCode(200);

        return result;

    }

    @Override
    public Result<List<CommentVo>> getAllComment(Integer postId) {
        Result<List<CommentVo>> result=new Result<>();
        List<CommentVo> commentVos = newsMapper.selectAllCommentByPostId(postId);
        if(commentVos.isEmpty()){
            result.setCode(200);
            result.setData(commentVos);
            return result;
        }
        commentVos.forEach(commentVo -> {
                commentVo.setCreatedTime(FormatTime.formatDateTime(commentVo.getTime()));
                if(commentVo.getReplies()!=null){
                    commentVo.getReplies().stream().forEach(reply -> {
                        reply.setCreatedTime(FormatTime.formatDateTime(reply.getTime()));
                    });
                }
        });
        result.setData(commentVos);
        return result;
    }

    @Override
    public Result<Object> updatePost(PublishPost post, MultipartFile coverImage, MultipartFile image, Integer postId) throws Exception {
       Result result=new Result();
       Post newsPost = new Post();
       //处理标题
        String title = post.getTitle();
        if(title.isEmpty() || title.trim().equals("")){
            return result.error("标题不能为空");
        }
        //处理封面
        String cover = "";
        if(coverImage != null && coverImage.getContentType().contains("image/") ){
             cover = minioServiceImpl.uploadImage(coverImage);
        }
        //处理图片
        String url="";
        if(image!= null  && image.getContentType().contains("image/")){
            log.info("hh");
            url = minioServiceImpl.uploadImage(image);
        }
        //处理内容
        String content = post.getContent();
        if(content.isEmpty()){
            return result.error("内容不能为空");
        }
        //处理标签
        newsPost.setTitle(title);
        newsPost.setContent(content);
        newsPost.setCoverImage(cover);
        newsPost.setPostId(postId);
        newsPost.setPicture(url);

        if(post.getTagId()!=null){
            newsPost.setTagId(post.getTagId());
        }
        if(post.getTextStatus()!=null){
            newsPost.setTextStatus(post.getTextStatus());
        }
        newsPost.setCategoryId(1);

        newsMapper.updatePost(newsPost);

        result.setCode(200);
        result.setMessage("修改成功");
        return result;
    }

    @Override
    public ModelAndView redirectToCreator(HttpSession session) {
        ModelAndView mv= new ModelAndView();

        //搜索个人信息
        User userInfo = (User)session.getAttribute("userInfo");
        Map<String,Object> param = new HashMap<>();
        param.put("userId",userInfo.getUserId());
        User user = userMapper.selectUserByUserIdOrEmail(param);

        //全部新闻
        ArrayList<Post> posts = searchInUserPageMapper.searchMyNews(userInfo.getUserId(), "", "", "", 0, -1, 0, 9999);

        int size = posts.size();

        mv.addObject("posts", posts);
        mv.addObject("user", user);
        mv.addObject("count", size);
        mv.setViewName("Creator-Center");

        return mv;

    }

    @Override
    public Result<UpdatePost> getPostById(Integer postId) {
        UpdatePost post = newsMapper.findUpdatePostByPostId(postId);
        if(post==null){
            return Result.error("该文章不存在");
        }
        return Result.success(post);

    }

    @Override
    public Result<Map<String, Object>> findPost(Integer pageNum, Integer userId,Integer categoryId, Integer auditStatus, Integer textStatus, HttpSession session) {
        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response = new HashMap<>();
        //处理请求参数
        Map<String, Object> param = new HashMap<>();
        if(pageNum <= 0){
            result.setMessage("参数错误");
            result.setCode(400);
            return result;
        }
        if(categoryId!=null){
            param.put("category", categoryId);
        }
        if(auditStatus!=null){
            param.put("audit_status", auditStatus);
        }
        if(textStatus!=null){
          param.put("text_status", textStatus);
        }
        if(userId!=null){
            param.put("userId", userId);
        }else {
            User userInfo = (User)session.getAttribute("userInfo");
            if(userInfo == null){
                result.setMessage("请先登录");
                result.setCode(400);
                return result;
            }else {
                param.put("userId", userInfo.getUserId());
            }
            param.put("userId", userInfo.getUserId());
        }
        int totalCount = postMapper.totalCount(param);
        if(totalCount ==0 ){
            result.setMessage("暂时没有内容");
            result.setCode(200);
            return result;
        }
        Double totalPage = Math.ceil((double)totalCount / PAGE_SIZE);
        if(pageNum >totalPage){
            result.setCode(400);
            result.setMessage("参数错误");
            return result;
        }

        int start = (pageNum - 1) * PAGE_SIZE;
        param.put("start", start);
        List<PostDTO> posts = postMapper.findPost(param);


        boolean hasMore = (pageNum * 10) < totalCount;
        response.put("posts", posts);
        response.put("hasMore", hasMore);
        response.put("totalCount", totalCount);
        response.put("totalPage", totalPage);
        result.setData(response);
        result.setCode(200);
        return result;
    }

    @Override
    public Result<Map<String, Object>> deleteAndJudge(Integer postId, HttpSession session) {
        if(!cheaklogin(session)){
            return Result.unauthorized("请先登录");
        }
        Result<Map<String,Object>> result=new Result<>();
        Map<String,Object> response = new HashMap<>();
        User userInfo = (User)session.getAttribute("userInfo");
        int userId = userInfo.getUserId();
        Comment deleteComment = newsMapper.selectcomment(postId);
        if(deleteComment==null){
            result.setCode(200);
            result.setMessage("评论不存在");
            return result;
        }
        if(deleteComment.getUserId()!=userId){
            result.setCode(400);
            result.setMessage("您没有权限删除该评论");
            return result;
        }
        newsMapper.deleteComment(postId);
        newsMapper.reduceCommentCount(postId);
        result.setCode(200);
        result.setMessage("删除成功");
        return result;
    }


}